package com.starblink.android.basic.base.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.view.MotionEvent
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.starblink.android.basic.base.IBaseView
import com.starblink.android.basic.receiver.ConnectivityReceiver
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.basic.ext.nowTime
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.StatusBarUtils


/**
 * 最底层的Activity,不带MVP和MVVM,一般不用这个
 */
abstract class AbsActivity() : AppCompatActivity(), IBaseView,
    ConnectivityReceiver.ConnectivityReceiverListener {


    /**
     * 获取Context对象
     */
    protected lateinit var mActivity: Activity
    protected lateinit var mContext: Context
    protected var pageExposureValue: Int? = null
//    abstract fun setContentView()

    // true: black icon / false: white icon
    protected open fun isStatusBarLightMode() = false


    /**
     * 从intent中解析数据，具体子类来实现
     */
    open protected fun getDataFromIntent(intent: Intent) {}

    /**
     * 设置顶部状态栏的颜色（默认为白色背景-黑色文字）
     */
    protected fun setStatusBarColor(): Int {
        //如果状态栏文字能变黑那么背景设置为白色，否则返回背景灰色文本默认为白色
        return if (StatusBarUtils.setStatusBarBlackText(this)) {
            Color.WHITE
        } else {
            Color.parseColor("#B0B0B0")
        }
    }

    /**
     * 动态的设置状态栏颜色
     * 当颜色为白色的时候显示白底黑字
     * 其他颜色为其他颜色底白色字
     * 一般由子类重写
     */
    fun setStatusBarColor(color: Int) {

        if (color == Color.WHITE) {
            //变黑色文字成功
            if (StatusBarUtils.setStatusBarBlackText(this)) {
                StatusBarUtils.setColor(this, Color.WHITE)
            } else {
                StatusBarUtils.setColor(this, Color.parseColor("#B0B0B0"))
            }

        } else {

            //变为白色文字成功
            StatusBarUtils.setStatusBarWhiteText(this)
            StatusBarUtils.setColor(this, color)

        }
    }

    fun setStatusBarBlackText() {
        StatusBarUtils.setStatusBarBlackText(this)
    }

    fun setStatusBarWhiteText() {
        StatusBarUtils.setStatusBarWhiteText(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        //改主题
        BarUtils.setStatusBarLightMode(this, isStatusBarLightMode())
        BarUtils.transparentStatusBar(this)
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
//        setContentView()
        mActivity = this
        mContext = this.applicationContext


        //获取intent传递的数据
        if (intent != null) {
            getDataFromIntent(intent)
        }

        /** 管理Activity的栈  */
        ActivityStackManage.addActivity(this)

        if (needRegisterNetworkChangeObserver()) {
            ConnectivityReceiver.registerObserver(this)
            ConnectivityReceiver.registerAnnotationObserver(this)
        }

    }


    /**
     * 是否需要注册监听网络变换
     */
    open protected fun needRegisterNetworkChangeObserver(): Boolean {
        return false
    }


    /**
     * 只映射了onDestroy方法
     */
    override fun onDestroy() {
        super.onDestroy()

        ActivityStackManage.removeActivityStack(this)

        if (needRegisterNetworkChangeObserver()) {
            ConnectivityReceiver.unregisterObserver(this)
            ConnectivityReceiver.unregisterAnnotationObserver(this)
        }
    }

    override fun popSelf() {
        finish()
    }


    override fun switchNetConfig() {}


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (v is EditText) {
                val outRect = Rect()
                v.getGlobalVisibleRect(outRect)
                if (!outRect.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
                    v.clearFocus()
                    KeyboardUtils.hideSoftInput(this)
                }
            } else {
                KeyboardUtils.hideSoftInput(this)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /*override fun onResume() {
        super.onResume()
        if (pageExposureValue != null) {
            pageExposure(pageExposureValue!!)
        }
    }*/

    open fun spmPageId(): Int = 0

    open fun spmPageParams(): Map<String, String> = mapOf()

    open fun isSpmTrackWithLifecycle(): Boolean = false

    private var trackTimeTag = 0L

    protected open fun pageExposure(
        pageElementValue: Int = spmPageId(),
        params: Map<String, String> = spmPageParams()
    ) {
        this.pageExposureValue = pageElementValue
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.pageExposure.value,
                spmCnt = GTrackerAssistUtils.fetchPageValue(pageElementValue),
                params = params
            )
        )
        trackTimeTag = nowTime()
    }

    protected open fun pageDisappear(
        pageElementValue: Int = spmPageId(),
        params: Map<String, String> = spmPageParams()
    ) {
        this.pageExposureValue = pageElementValue
        val delay = nowTime() - trackTimeTag
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.pageStayTime.value,
                spmCnt = GTrackerAssistUtils.fetchPageValue(pageElementValue),
                params = mutableMapOf<String, String>().apply {
                    putAll(params)
                    put("duration", delay.toString())
                }
            )
        )
    }

    override fun onResume() {
        super.onResume()
        if (isSpmTrackWithLifecycle()) {
            pageExposure()
        }
    }

    override fun onPause() {
        super.onPause()
        if (isSpmTrackWithLifecycle()) {
            pageDisappear()
        }
    }


}
